/**
 * File: HtmlTag.java
 * User: z3y2
 * Date: 2010-12-23
 * Time: 上午10:34:52
 * Copyright: (c) 2010 All Rights Reserved
 */
package com.mypack.web.taglib;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * 自定义标签 -- > <html:base/>
 * 输出 --> <base href="http://localhost:8080/app/">
 * @author z3y2
 */
public class HtmlBaseTag extends TagSupport {

	
	/** 
	 * override super class method
	 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag() 
	 */
	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		ServletContext logger = pageContext.getServletContext();
		
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() 
			+ ":" + request.getServerPort() + path + "/";
		
		logger.log("basePath = " + basePath);
		
		JspWriter out = pageContext.getOut();
		
		try {
			out.print("<base href=\""+ basePath +"\">");
			out.flush();
		} catch (IOException e) {
			logger.log(e.getMessage(), e); // 记录异常
			throw new JspException(e.getMessage(), e);
		}
		
		// 这个地方不能关闭流,不然整个页面无法再向外输出.
		
		return SKIP_BODY;
	}
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

}
